<template>
	<view class="auth">
		<up-form :model="form" :up="up" label-width="90px" ref="formRef">
			<view class="form_part">
				<up-form-item label="当前手机号" prop="captainPhone" border-bottom>
					<up-input type="number" border="none" v-model="form.captainPhone" placeholder="请输入当前手机号"></up-input>
				</up-form-item>
			</view>

			<view class="form_part">
				<ssection title="请上传本人有效身份证(必填)" line></ssection>
				<view class="file_box">
					<view style="margin-right: 20px;">
						<view class="image_part" style="padding: 10px;">
							<image :src="images.idCardPic1" @click="() => uploadImage('idCardPic1', 0, 1)">
							</image>
						</view>
						<view class="file_title">身份证正面</view>
					</view>
					<view>
						<view class="image_part" style="padding: 10px;">
							<image :src="images.idCardPic2" @click="() => uploadImage('idCardPic2', 0, 0)">
							</image>
						</view>
						<view class="file_title">身份证反面</view>
					</view>
				</view>
			</view>
			<view class="form_part">
				<up-form-item label="船长姓名" border-bottom prop="captainName">
					<up-input border="none" v-model="form.captainName" placeholder="上传身份证,系统自动识别"></up-input>
				</up-form-item>
				<up-form-item label="身份证号" border-bottom prop="idCard">
					<up-input border="none" v-model="form.idCard" placeholder="上传身份证,系统自动识别"></up-input>
				</up-form-item>
				<up-form-item label="有效时间" border-bottom prop="idStartDate" @click="showOrClose(1, 'idStartDate')">
					<up-input border="none" v-model="form.idStartDate" placeholder="上传身份证,系统自动识别" disabled
						disabledColor="#fff"></up-input>
				</up-form-item>
				<up-form-item label="结束时间" border-bottom prop="idEndDate" @click="showOrClose(1, 'idEndDate')">
					<up-input border="none" v-model="form.idEndDate" placeholder="上传身份证,系统自动识别" disabled
						disabledColor="#fff"></up-input>
				</up-form-item>
			</view>
			<view class="form_part">
				<ssection title="请上传本人适任证(必填)" line></ssection>
				<view class="file_box">
					<view>
						<view class="image_part">
							<image :src="images.certificate" @click="() => uploadImage('certificate')"></image>
						</view>
						<view class="file_title">适任证正面</view>
					</view>
					<view>
						<view class="image_part">
							<image :src="images.certificate2" @click="() => uploadImage('certificate2')"></image>
						</view>
						<view class="file_title">适任证副面</view>
					</view>
				</view>
			</view>
			<view class="form_part">
				<up-button type="primary" color="rgb(0,129,255)" customStyle="borderRadius:5px" @click="auth"
					:loading="btnLoading" loadingText="正在保存">保存</up-button>
			</view>
		</up-form>
	</view>
	<up-datetime-picker v-model="defaultDate" :show="selectDateShow" :minDate="0" :maxDate="32503651199000" mode="date"
		@cancel="showOrClose(0)" @confirm="confirmDate"></up-datetime-picker>
	<up-toast ref="uToastRef"></up-toast>
</template>


<script setup>
import ssection from '@/components/ssection.vue'
import {
	chooseImage,
	getImage,
	uploadFiles
} from '@/api/file.js'
import {
	ref,
	reactive,
	nextTick
} from 'vue'
import {
	onLoad
} from "@dcloudio/uni-app"
import idCardPic1 from "@/static/images/mine/Portraitface.png"
import idCardPic2 from "@/static/images/mine/National.png"
import certificate from "@/static/images/mine/qualCertificate.png"
import certificate2 from "@/static/images/mine/qualCertificate.png"
import {
	getInfo,
	Entlist,
	toAuth,
	updateAssignorInfo
} from '@/api/captain.js'
import normalizeDate from '@/utils/dateFormat.js'


/* 数据 */
const uToastRef = ref(null)
const formRef = ref(null)
// 表单
const form = reactive({
	captainName: '',
	captainPhone: '',
	idCard: '',
	idEndDate: '',
	idStartDate: '',

	idCardPic1: '',
	idCardPic2: '',
	certificate: '',
	certificate2: ''
})
// 校验规则
const relus = reactive({
	captainName: [{
		required: true,
		message: '姓名不能为空',
		trigger: ['blur', 'change']
	}],
	captainPhone: [{
		required: true,
		message: '手机号不能为空',
		trigger: ['blur', 'change']
	}, {
		pattern: /(^1[3-9][0-9]{9}$)/g,
		message: '手机格式错误',
		trigger: ['blur', 'change']
	}],
	'idCard': [{
		required: true,
		message: '身份证号不能为空',
		trigger: ['blur', 'change']
	}, {
		pattern: /(^\d{15}$)|(^\d{17}[\dxX]$)/g,
		message: '请输入正确的身份证号',
		trigger: ['blur', 'change']
	}],
	idStartDate: [{
		required: true,
		message: '开始时间不能为空',
		trigger: ['blur', 'change']
	}],
	idEndDate: [{
		required: true,
		message: '结束时间不能为空',
		trigger: ['blur', 'change']
	}]
})
const images = reactive({
	idCardPic1,
	idCardPic2,
	certificate,
	certificate2
})
const ass_images = reactive({
	idCardPic1,
	idCardPic2
})
// 按钮加载
const btnLoading = ref(false)
// 是否有关联企业
const isHasEnt = ref(false)
const role = ref('')
const selectDateShow = ref(false)
const defaultDate = ref(Date.now())
const dateKey = ref('')





/* 函数 */
const formatDate = (date) => {
	const d = new Date(date)
	const year = d.getFullYear()
	const month = String(d.getMonth() + 1).padStart(2, '0')
	const day = String(d.getDate()).padStart(2, '0')
	return `${year}-${month}-${day}` // 输出: 2023-05-20
}
// 选择时间
const confirmDate = (e) => {
	form[dateKey.value] = formatDate(e.value)
	showOrClose(0)
}
// 打开或者关闭时间选择
const showOrClose = (type, key) => {
	// type 0 关闭 1 打开
	if (type === 0) {
		selectDateShow.value = false
	} else {
		if (form[key]) {
			defaultDate.value = new Date(form[key]).getTime()
		} else {
			defaultDate.value = Date.now()
		}
		dateKey.value = key
		selectDateShow.value = true
	}
}
// 获取用户信息
const getUserInfo = async () => {
	uToastRef.value.show({
		message: '加载中...',
		type: 'loading',
		duration: -1
	})
	let res = await getInfo()
	uToastRef.value.hide()
	if (res.success) {
		Object.assign(form, {
			...res.data,
			idStartDate: normalizeDate(res.data.idStartDate, true),
			idEndDate: normalizeDate(res.data.idEndDate, true)
		})
		for (let key in images) {
			if (form[key]) {
				getImage(form[key]).then(res => {
					images[key] = res.data
				})
			}
		}
	}
}
// 获取用户是否已关联企业
const getUserEnt = async () => {
	uToastRef.value.show({
		message: '加载中...',
		type: 'loading',
		duration: -1
	})
	let res = await Entlist()
	uToastRef.value.hide()
	if (res.success) {
		isHasEnt.value = res.data && res.data.length > 0
	}
}
// 上传图片
const uploadImage = async (type, licenseType = 9, cardType = 0) => {
	/* 上传图片 */
	chooseImage().then(async (image) => {
		uToastRef.value.show({
			message: '正在上传',
			type: 'loading',
			duration: -1
		})
		let res = await uploadFiles(image, {
			licenseType,
			cardType
		})
		uToastRef.value.hide()
		if (res.success) {
			images[type] = image
			let data = res.data
			form[type] = data.fileId

			let ret = data.certificateInfo
			let id_dic = {
				'name': 'captainName',
				'iDNumber': 'idCard',
			}
			if (type === 'idCardPic1') {
				for (let key in ret) {
					if (Object.keys(id_dic).includes(key)) {
						form[id_dic[key]] = ret[key]
					}
				}
			} else if (type === 'idCardPic2') {
				form.idStartDate = normalizeDate(ret.startDate)
				form.idEndDate = normalizeDate(ret.endDate)
			}
		}
	})
}
// 保存
const auth = async () => {
	let valid = await formRef.value.validate()
	if (!valid) {
		uToastRef.value.show({
			message: '请完成表单',
			type: 'warning'
		})
		return
	}
	let imgs = role.value === 'captain' ? Object.keys(images) : Object.keys(ass_images)
	for (let key of imgs) {
		if (!form[key]) {
			uToastRef.value.show({
				message: '请先把图片都上传',
				type: 'warning'
			})
			return
		}
	}
	btnLoading.value = true

	// await afterEntCheck()

	if (isHasEnt.value) {
		// 已经关联了企业逻辑
		await afterEntCheck()
	} else {
		// 没有关联企业了逻辑
		if (!relateEntCode.value) {
			uToastRef.value.show({
				message: '请先填写所属营运商邀请码',
				type: 'warning'
			})
			btnLoading.value = false
			return
		}
		uToastRef.value.show({
			message: '正在检测营运商',
			type: 'loading',
			duration: -1
		})
		// 查询结果是该邀请码的企业是否已经与用户关联api
		let isLink = await haslinkEnt(relateEntCode.value)
		uToastRef.value.hide()
		if (isLink) {
			// 查询结果是该邀请码的企业已经与用户关联
			await afterEntCheck()
		} else {
			// 查询结果是该邀请码的企业还没与用户关联
			uToastRef.value.show({
				message: '正在关联营运商',
				type: 'loading',
				duration: -1
			})
			// 用户关联企业api
			let res = await linkEnt(relateEntCode.value)
			uToastRef.value.hide()
			if (res.success) {
				await afterEntCheck()
			}
		}
	}
	btnLoading.value = false
}
// 已关联企业逻辑封装
const afterEntCheck = async () => {
	let obj = {
		...form
	}
	if (obj.idEndDate === "长期") {
		obj.idEndDate = '2999-12-31'
	}
	uToastRef.value.show({
		message: '正在保存',
		type: 'loading',
		duration: -1
	})
	let fn = null
	if (role.value === 'captain') {
		fn = toAuth
	} else {
		fn = updateAssignorInfo
	}
	// 认证api
	let res = await fn(obj)
	uToastRef.value.hide()
	if (res.success) {
		// 成功回调
		uToastRef.value.show({
			message: '保存成功',
			type: 'success',
			position: 'top',
			complete() {
				uni.navigateBack()
			}
		})
	}
}
// 初始化封装
const init = async () => {
	await getUserInfo()
	await getUserEnt()
}



/* 钩子 */
onLoad(async ({
	role: roles
}) => {
	if (roles) role.value = roles
	await nextTick()
	await init()
})
</script>

<style lang="scss" scoped>
.auth {
	.form_part {
		background-color: #fff;
		padding: 10px;
		box-sizing: border-box;
		margin-bottom: 10px;

		.file_box {
			display: flex;
			padding: 0 10px;

			>view {
				flex: 1;
				margin-right: 10px;

				&:last-child {
					margin-right: 0;
				}

				.image_part {
					width: 100%;
					aspect-ratio: 3 / 2;
					border: 1px solid #ddd;
					box-sizing: border-box;

					>image {
						width: inherit;
						height: 100%;
						display: block;
					}
				}

				.file_title {
					padding: 15px 0 5px;
					font-size: 14px;
					text-align: center;
				}
			}
		}

		.low_tip {
			color: rgb(64, 117, 247);
		}
	}
}
</style>